package org.biogroovy.search.eutils

import java.util.Map.Entry

import org.biogroovy.search.ISearchParamMapBuilder
import org.biogroovy.search.SearchParam
import org.biogroovy.search.SearchParamSet

class EntrezParamMapBuilder implements ISearchParamMapBuilder {


	@Override
	public Map<String, String> createPopulatedParamMap(SearchParamSet searchParams){
		Map<String, String> paramMap = new HashMap<>();
		
		constructTermEntry(searchParams, paramMap)

		SearchParam param = null;
		for(Entry<String, SearchParam> entry : searchParams.entrySet()){
			param = entry.value;
			if ((!param.isSubTerm && !param.isTerm) &&  param.hasValue()){
				paramMap.put(param.getParamName(), param.value);
			}
		}
		return paramMap;
	}



	@Override
	public Map<String, String> createParamMap(SearchParamSet searchParams){
		Map<String, String> paramMap = new HashMap<>();

		constructTermEntry(searchParams, paramMap);

		SearchParam param = null;
		for(Entry<String, SearchParam> entry : searchParams.entrySet()){

			param = entry.value;

			if (!param.isSubTerm && !param.isTerm){
				paramMap.put(param.getParamName(), param.value);
			}
		}

		return paramMap;
	}

	protected void constructTermEntry(SearchParamSet searchParams, Map<String, String> paramMap){

		SearchParam termParam = searchParams.getTerm();
		Set<SearchParam> subTerms = searchParams.getSubTerms();
		if(termParam != null){
			String termValue = termParam.value;
						
			boolean hasValue = (termValue != null);
			termValue = (hasValue)?termValue:"";
			
			if (hasValue && searchParams.hasPopulatedSubTerms()){
				termValue += " AND";
			}
			
			
			// always assume that the term parameter has a value.
			for(SearchParam subTerm : subTerms){
				
				if (subTerm.hasValue()){
					if (!termValue.equals("") && !termValue.endsWith("AND")){
						termValue += " AND";
					}
					termValue += " ${subTerm.value}[${subTerm.getParamName()}]"
				}
			}
			paramMap.put(termParam.getParamName(), termValue.trim());
		}
	}
}
